package it.polimi.swKnights.SWIMv2.servlets.help;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.helpRequest.ProcessHelpRequestRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ProcessHelpRequests
 */
public class ProcessHelpRequests extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		String userAsker = getAskingUserFrom((String) request
				.getParameter("help_req_id"));
		String id_request = getIdRequestFrom((String) request
				.getParameter("help_req_id"));
		String date_creation = getCreationDateFrom((String) request
				.getParameter("help_req_id"));

		HttpSession session = request.getSession();
		String userHelper = (String) session.getAttribute("userName");
		String password = (String) session.getAttribute("password");

		Boolean accepted = this.getTruthFromRadio((String) request
				.getParameter("radio_acceptance"));

		ProcessHelpRequestRemote procReq = this
				.lookUp(ProcessHelpRequestRemote.class);

		try
		{
			procReq.handleAnswerToHelpRequest(userAsker, id_request,
					date_creation, userHelper, password, accepted);
			//request.getRequestDispatcher("./seeHelpRequest").forward(request,
				//	response);
			request.getRequestDispatcher("WEB-INF/help/helpRequest.jsp")
			.forward(request, response);

		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.notuser);
		}

	}

	private String getIdRequestFrom(String attribute)
	{
		return this.getFromAttrib(attribute, 0);
	}

	private String getCreationDateFrom(String parameter)
	{
		return this.getFromAttrib(parameter, 1);
	}

	private String getAskingUserFrom(String attribute)
	{

		return this.getFromAttrib(attribute, 2);
	}

	private String getFromAttrib(String attrib, int num)
	{

		String s = "";
		try
		{
			s = this.getAttribs(attrib)[num];
		}
		catch (Exception e)
		{
			throw new IllegalArgumentException(
					"something wrong it should a string like  ID @ DATE @ USER_ASKER");
		}
		return s;
	}

	private String[] getAttribs(String attrib)
	{
		String[] S = null;
		S = attrib.split(" @ ");
		return S;
	}

}
